<template>
  <view class="add-desk form-ret-padd" :style="{ '--theme': themeColor }">
    <view v-if="type === 'add'">
      <u-popup
        :show="visible"
        mode="center"
        @close="close"
        @touchmove.stop.prevent
        :safeAreaInsetBottom="false"
        :closeOnClickOverlay="false"
        round="8"
      >
        <view class="add-area">
          <view class="flex title">
            <view
              :class="['flex1', 'center', index == active ? 'active' : '']"
              v-for="(item, index) in addType"
              :key="index"
              @click="changeTab(index)"
              >{{ item }}</view
            >
          </view>
          <u--form :model="form" :rules="rules" ref="form">
            <u-form-item
              prop="name"
              labelWidth="0rpx"
              @click="showSelect = true"
            >
              <view class="border-item flex">
                <u--input
                  v-model="form.name"
                  disabled
                  disabledColor="#ffffff"
                  border="none"
                  placeholder="请选择区域"
                />
                <u-icon slot="right" name="arrow-down" />
              </view>
            </u-form-item>

            <u-form-item prop="tableNo" labelWidth="0rpx">
              <view class="show-count">
                <u--input
                  v-model="form.tableNo"
                  height="20"
                  :maxlength="active == 0 ? 4 : 2"
                  :type="active == 0?'text':'number'"
                  :placeholder="`${
                    active === 0 ? '请输入桌位号码' : '请输入桌位数量'
                  }`"
                />
                <view class="num flex center"
                  >{{ form.tableNo.length || 0 }}/{{
                    active == 0 ? 4 : 2
                  }}</view
                >
              </view>
            </u-form-item>
          </u--form>
          <view
            v-if="active == 1"
            class="text-28"
            :style="{
              color: '#888',
            }"
            >请按照实际桌位数量输入，输入保存后将按照数字依次增加</view
          >
        </view>
        <view class="flex btns">
          <view @click="close()" class="flex1 center">取消</view>
          <view @click="save()" class="flex1 center save">保存</view>
        </view>
      </u-popup>
    </view>
    <view v-else>
      <u-popup
        :show="editVisible"
        mode="center"
        @close="close"
        @touchmove.stop.prevent
        :safeAreaInsetBottom="false"
        :closeOnClickOverlay="false"
        round="8"
      >
        <view class="add-area">
          <view class="flex center title"> 编辑座位号 </view>
          <u--form :model="editForm" :rules="rules" ref="editForm">
            <u-form-item
              props="areaName"
              labelWidth="0rpx"
              @click="showSelect = true"
            >
              <view class="border-item flex">
                <u--input
                  v-model="areaName"
                  disabled
                  disabledColor="#ffffff"
                  border="none"
                />
                <u-icon slot="right" name="arrow-down" />
              </view>
            </u-form-item>
            <u-form-item prop="tableNo" labelWidth="0rpx">
              <view class="show-count">
                <u--input
                  v-model="editForm.tableNo"
                  height="20"
                  :maxlength="active == 0 ? 4 : 2"
                  :placeholder="`${
                    active == 0 ? '请输入桌位号码' : '请输入桌位数量'
                  }`"
                />
                <view class="num flex center"
                  >{{ editForm.tableNo.length || 0 }}/{{
                    active == 0 ? 4 : 2
                  }}</view
                >
              </view>
            </u-form-item>
            <view v-show="editForm.codeNo" class="text-26 bind-code">
              已绑定：{{ editForm.codeNo }}
            </view>
          </u--form>
          <view v-if="active == 1"
            >请按照实际桌位数量输入，输入保存后将按照数字依次增加</view
          >
        </view>
        <view class="flex btns">
          <view @click="close()" class="flex1 center">取消</view>
          <view @click="save()" class="flex1 center save">保存</view>
        </view>
      </u-popup>
    </view>
    <chooseArea
      :visible.sync="showSelect"
      :activeId="type == 'add' ? form.areaId : editForm.areaId"
      @setArea="setArea"
    />
  </view>
</template>
<script>
import { mapState } from "vuex";
import chooseArea from "../choose-area";
import {
  insertTable,
  getTables,
  batchInsertTable,
  updateTable,
} from "@/service/api/sp-product/index";

export default {
  components: {
    chooseArea,
  },
  data() {
    return {
      active: 0,
      type: "add",
      form: {
        areaId: "",
        tableNo: "",
        name: "",
      },
      showSelect: false,
      rules: {
        name: [
          {
            type: "string",
            required: true,
            message: "请选择区域",
            trigger: ["blur", "change"],
          },
        ],
        tableNo: [
          {
            type: "string",
            required: true,
            message: "请输入桌位号码",
            trigger: ["blur", "change"],
          },
          {
            validator: (rule, value, callback) => {
              if (this.active == 0) {
                return this.deskList.findIndex((item) => {
                  return item.tableNo == value;
                }) > -1
                  ? false
                  : true;
              } else {
                return true;
              }
            },
            message: `桌位号码重复，请重新输入`,
            trigger: ["change", "blur"],
          },
        ],
      },
      editRules: {
        tableNo: [
          {
            type: "string",
            required: true,
            message: "请输入桌位号码",
            trigger: ["blur", "change"],
          },
          {
            validator: (rule, value, callback) => {
              let item = this.deskList.filter((item) => {
                return item.tableNo == value;
              });
              let { editForm } = this;
              if (item.length > 0) {
                if (
                  editForm.areaId === item[0].areaId &&
                  editForm.id === item[0].id
                ) {
                  return true;
                } else {
                  return false;
                }
              } else {
                return true;
              }
            },
            message: `桌位号码重复，请重新输入`,
            trigger: ["change", "blur"],
          },
        ],
      },
      addType: ["单个添加", "批量添加"],
      deskList: [],
      visible: false,
      editVisible: false,
      editForm: {},
    };
  },
  components: {},
  computed: {
    ...mapState("sp-common/auth", ["pubUserInfo"]),
    ...mapState("sp-commodity/index", ["areaList"]),
    areaName() {
      if (this.editForm.areaId) {
        return this.areaList.filter((item) => {
          return this.editForm.areaId == item.id ? item.name : "";
        })[0].name;
      }
    },
    themeColor({ $theme }) {
      return $theme.themeColor.primary;
    },
  },
  methods: {
    open(row) {
      this.type = row ? "edit" : "add";
      // this.form.specVal = row ? row : "";
      // this.visible = true;
      if (this.type == "edit") {
        this.editForm = row;
        this.editVisible = true;
        this.$nextTick(() => {
          this.$refs.editForm.setRules(this.editRules);
          this.getDesk();
        });
      } else {
        this.visible = true;
        this.$nextTick(() => {
          this.$refs.form.setRules(this.rules);
        });
      }
    },
    close(status) {
      if (this.type === "add") {
        this.visible = false;
        this.form = {
          areaId: "",
          tableNo: "",
          name: "",
        };
        this.$refs.form.clearValidate();
        this.$refs.form.resetFields();
        if (status === true) {
          uni.showToast({
            title: "新增桌号成功",
            icon: "none",
          });
          this.$parent.getDesk(1);
        }
        this.active = 0;
      } else {
        this.editForm = {};
        this.editVisible = false;
        this.$refs.editForm.clearValidate();
        this.$refs.editForm.resetFields();
        if (status) {
          this.$parent.getDesk(1);
        }
      }
    },
    save() {
      if (this.type === "add") {
        this.$refs.form.validate().then((res) => {
          let {
            form,
            active,
            pubUserInfo: {
              pubDomainShopVo: { id: pubDomainShopId },
            },
          } = this;
          let { tableNo, areaId } = form;
          if (active === 0) {
            let query = { pubDomainShopId, tableNo, areaId };
            insertTable(query).then((res) => {
              this.close(true);
            });
          } else {
            let query = { pubDomainShopId, num: tableNo, areaId };
            batchInsertTable(query).then((res) => {
              this.close(true);
            });
          }
        });
      } else {
        this.$refs.editForm.validate().then((res) => {
          let { codeNo, pubDomainBusinessId, pubDomainShopId, ...query } =
            this.editForm;
          query.pubDomainShopId = this?.pubUserInfo?.pubDomainShopVo?.id;
          updateTable(query).then(() => {
            this.close(true);
          });
        });
      }
    },
    setArea(item) {
      if (this.type === "add") {
        this.form.areaId = item.id;
        this.form.name = item.name;
      } else {
        this.editForm.areaId = item.id;
      }
      this.showSelect = false;
      this.getDesk();
    },
    getDesk() {
      let {
        pubUserInfo: {
          pubDomainShopVo: { id: pubDomainShopId },
        },
        form: { areaId },
        type,
        editForm,
      } = this;
      let queryParams = {
        pubDomainShopId,
        pageNum: 1,
        pageSize: 999,
        areaId,
      };
      if (type === "edit") {
        queryParams.areaId = editForm.areaId;
      }
      getTables(queryParams).then((res) => {
        this.deskList = res.list;
        if (this.type === "add") {
          this.$refs.form.validateField("tableNo");
        } else {
          this.$refs.editForm.validateField("tableNo");
        }
      });
    },
    changeTab(index) {
      this.active = index;
      this.form.tableNo = ''
      this.rules.tableNo[0].message =
        this.active == 0 ? "请输入桌位号码" : "请输入桌位数量";
      this.$refs.form.clearValidate();
    },
  },
};
</script>
<style lang="scss" scoped>
.add-area {
  width: calc(100vw - 250rpx);
  padding: 40rpx 45rpx 25rpx;
  .title {
    font-size: 32rpx;
    font-weight: bold;
    color: #131313;
    margin-bottom: 25rpx;
    .active {
      color: var(--theme);
    }
  }
}
.border-item {
  border: 1px solid #e7e7e7;
  height: 64rpx;
  align-items: center;
  border-radius: 8rpx;
  padding: 0 20rpx;
}
.btns {
  border-radius: 0rpx 0 12rpx 12rpx;
  overflow: hidden;
  view {
    height: 80rpx;
    color: var(--theme);
    border-top: 1px solid #eee;
  }
  .save {
    background-color: var(--theme);
    color: #fff !important;
    border-color: var(--theme) !important;
  }
}
.area-list {
  height: 66vh;
  .top {
    padding: 30rpx 20rpx 35rpx;
    font-size: 30rpx;
    font-weight: 500;
    color: #131313;
    border-bottom: 1rpx solid #c7c7c7;
  }
  .list {
    padding: 0 40rpx;
    width: calc(100% - 80rpx);
    .class {
      font-size: 30rpx;
      color: #131313;
      font-weight: 500;
      height: 50rpx;
      margin-bottom: 15rpx;
      margin-top: 30rpx;
      .active {
        color: var(--theme) !important;
      }
    }
  }
}
.bind-code{
  color: #131313;
  // padding-left: 20rpx;
}
</style>
